package com.yunfeisoft.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.applet.base.BaseServiceImpl;
import com.applet.sql.separation.DataSourceChange;
import com.applet.utils.Page;
import com.yunfeisoft.business.dao.inter.SmsHomeBrandDao;
import com.yunfeisoft.business.model.PmsBrand;
import com.yunfeisoft.business.model.SmsHomeBrand;
import com.yunfeisoft.business.service.inter.SmsHomeBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: SmsHomeBrandServiceImpl
 * Description: 首页推荐品牌表service实现
 * Author: Jackie liu
 * Date: 2020-06-02
 */
@Service("smsHomeBrandService")
public class SmsHomeBrandServiceImpl extends BaseServiceImpl<SmsHomeBrand, String, SmsHomeBrandDao> implements SmsHomeBrandService {

    @Autowired
    private SmsHomeBrandDao smsHomeBrandDao;

    @Override
    @DataSourceChange(slave = true)
    public Page<SmsHomeBrand> queryPage(Map<String, Object> params) {
        return getDao().queryPage(params);
    }

    /**
     * 添加首页推荐品牌
     * @param multipleSelection
     * @return
     */
    @Transactional
    @Override
    public Map<String, Object> saveHomeBrand(String multipleSelection) {
        Map<String, Object> result = new HashMap<>();
        // 将参数转为品牌列表
        List<PmsBrand> pmsBrandList = JSON.parseArray(multipleSelection, PmsBrand.class);
        for (PmsBrand pmsBrand : pmsBrandList) {
            // 查询品牌是否已被添加
            List<SmsHomeBrand> smsHomeBrandList = smsHomeBrandDao.queryByBrandId(pmsBrand.getId());
            if (!ObjectUtils.isEmpty(smsHomeBrandList)) {
                result.put("flag", false);
                result.put("message", "品牌已被添加!");
                return result;
            }
        }
        // 新增
        pmsBrandList.stream().forEach(pmsBrand -> {
            SmsHomeBrand smsHomeBrand = new SmsHomeBrand();
            smsHomeBrand.setBrandId(pmsBrand.getId());
            smsHomeBrand.setBrandName(pmsBrand.getName());
            // 排序默认为0
            smsHomeBrand.setSort(0);
            // 默认不推荐0
            smsHomeBrand.setRecommendStatus(0);
            save(smsHomeBrand);
        });
        result.put("flag", true);
        result.put("message", "添加品牌成功!");
        return result;
    }

    /**
     * 查询首页推荐品牌列表
     * @param limit
     * @return
     */
    @Override
    public List<SmsHomeBrand> queryHomeBrandIndex(int limit) {
        return getDao().queryHomeBrandIndex(limit);
    }
}